<?php

@ini_set( 'upload_max_size' , '64M' );
@ini_set( 'post_max_size', '64M');
@ini_set( 'max_execution_time', '300' );

if ( ! isset( $content_width ) ) $content_width = 960;

set_user_setting( 'dfw_width','500' );

/* Automatic updates for All themes: */
add_filter( 'auto_update_theme', '__return_true' );

/* Automatic updates for All plugins: */
add_filter( 'auto_update_plugin', '__return_true' );

/* To enable automatic updates for major releases or development purposes, the place to start is with the WP_AUTO_UPDATE_CORE constant. Defining this constant one of three ways allows you to blanket-enable, or blanket-disable several types of core updates at once.
 */
define( 'WP_AUTO_UPDATE_CORE', true );

/**
 * the theme version
 */
define('ORANGE_VERSION', '1.0');

/**
 * load theme feature before display
 */
function set_up(){

    require_once(get_template_directory() . '/inc/widgets.php');
    require_once(get_template_directory() . '/inc/customizer.php');

    load_theme_textdomain( 'orange', get_template_directory() . '/languages' );

    register_nav_menus(array(
        'primary'   =>  __('页面顶部导航菜单', 'orange'),
        'social'    =>  __('页面底部社交媒体', 'orange'),
        'law'       =>  __('页面底部法律相关', 'orange' ),
    ));
   
}
add_action( 'after_setup_theme', 'set_up' );

// Register Theme Features
function custom_theme_features(){

    // Support featured image
    add_theme_support( 'post-thumbnails' );
    // set_post_thumbnail_size( 200, 400 );

    add_theme_support( "title-tag" );

    // Support link
    add_filter( 'pre_option_link_manager_enabled', '__return_true' );

    add_theme_support( 'automatic-feed-links' );

    add_theme_support( 'custom-background' );

    add_theme_support( 'custom-logo',  array(
        'height'      => 100,
        'width'       => 478,
        'flex-height' => true,
        'flex-width'  => true,
        'header-text' => array( 'site-title', 'site-description' )
    ) );
    
    add_editor_style();

    // Add theme support for Custom Header
    $header_args = array(
        'default-image'          => get_template_directory_uri() . '/images/header.jpg',
        'width'                  => 1920,
        'height'                 => 170,
        'flex-width'             => true,
        'flex-height'            => true,
        'uploads'                => true,
        'random-default'         => false,
        'header-text'            => true,
        'default-text-color'     => 'Site Name',
        'wp-head-callback'       => '',
        'admin-head-callback'    => '',
        'admin-preview-callback' => '',
    );
    add_theme_support( 'custom-header', $header_args );
}
add_action( 'after_setup_theme', 'custom_theme_features' );

// 初始化widgets
add_action( 'widgets_init', 'widgets_init' );
function widgets_init() {

    register_sidebar( array(
        'name'          => __( '文章侧栏', 'orange' ),  // 侧栏的名字
        'id'            => 'orange',    // 唯一的ID
        'class'         => 'post',  // 这个class以sidebar-class的形式在后台面板显示
        'description'   => __( 'post的侧栏.', 'orange' ),  // 描述
        'before_widget' => '<li id="%1$s" class="widget zengxiaoluan %2$s">',   // 用什么标签包裹一个widget
        'after_widget'  => '</li>',     // 结尾
        'before_title'  => '<h3 class="widgettitle">',  // 小工具的开头
        'after_title'   => '</h3>',     // 结尾
    ) );

    register_sidebar( array(
        'name'          => __( '页面侧栏', 'orange' ),
        'id'            => 'banana',
        'class'         => 'page',
        'description'   => __( 'page的侧栏.', 'orange' ),
        'before_widget' => '<li id="%1$s" class="widget %2$s">',
        'after_widget'  => '</li>',
        'before_title'  => '<h2 class="bananatitle">',
        'after_title'   => '</h2>',
    ) );

    register_sidebar( array( 
        'name'          => __( '合作伙伴', 'orange' ),
        'id'            => 'cooperation',
        'description'   => __( '展示合作伙伴的logo。', 'orange' ),
        'class'         => 'cooperation',
        'before_widget' => '<div class="col-md-2 col-sm-4 col-xs-6">',
        'after_widget'  => '</div>'
    ) );
}

// load scripts
function orange_scripts(){
    global $orange_version;

    if ( is_singular() ) wp_enqueue_script( "comment-reply" );

    // css
    wp_enqueue_style('normalize', get_template_directory_uri() . '/css/normalize.css');
    wp_enqueue_style('style', get_template_directory_uri() . '/style.css',['normalize'], ORANGE_VERSION);
    wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css');
    wp_enqueue_style('animate', get_template_directory_uri() . '/css/animate.css');
    wp_enqueue_style('font-awesome', get_template_directory_uri() . '/css/font-awesome.min.css');

    if ( wp_is_mobile() ) {
        wp_enqueue_style('mobile', get_template_directory_uri() . '/css/mobile.css');        
    }

    // scripts
    wp_enqueue_script('jquery');
    wp_enqueue_script('bootstrap', get_template_directory_uri() . '/scripts/bootstrap.min.js',[], '3.3.7', true);
    wp_enqueue_script('orange', get_template_directory_uri() . '/scripts/orange.js',['bootstrap'], ORANGE_VERSION, true);

    // Load the html5 shiv.
    // wp_enqueue_script( 'orange-html5', get_template_directory_uri() . '/scripts/html5.js', array(), '3.7.3' );
    // wp_script_add_data( 'orange-html5', 'conditional', 'lt IE 9' );

    if (is_404()) {
        // wp_enqueue_script( '404', get_template_directory_uri() . '/scripts/404.js', array(  ), ORANGE_VERSION, true );
        // wp_enqueue_style( '404', get_template_directory_uri() . '/css/404.css', array(  ), ORANGE_VERSION, 'all' );
    }

    if (is_home()) {
        // wp_enqueue_script( 'parallax', get_template_directory_uri() . '/scripts/jquery.parallax.min.js', array(  ), ORANGE_VERSION, true );
    }

}
add_action('wp_enqueue_scripts', 'orange_scripts');


function new_excerpt_more( $more ) {
    return ' <a class="read-more" href="'. get_permalink( get_the_ID() ) . '">' . __('查看详情', 'orange') . '</a>';
}
add_filter( 'excerpt_more', 'new_excerpt_more' );

function seo(){

    if (is_home()) {
        $description = __( '湖南文沥征信数据服务有限公司（简称文沥），于2014年在长沙注册正式成立。文沥定位于数据时代领先的金融科技公司，以大数据技术风控为手段，连接整合企业实时经营数据，促进传统金融行业的产品创新，为金融机构效率的提升提供全面的金融数字化服务，使一部分小微企业实现普恵金融成为可能。', 'orange' );
        $keywords = get_option('blogdescription').','.get_option('blogname');
    }else{
        $description = get_the_title();
        $keywords = get_the_tag_list();
        if (empty($keywords)) {
            $keywords = __( '湖南文沥征信数据服务有限公司', 'orange' );
        }else{
            $keywords = preg_replace('/<a href=".*?" rel="tag">/i', ',', $keywords);
            $keywords = preg_replace('/<\/a>/i', '', $keywords);
            $keywords = trim($keywords,',');
        }
    }
    
    echo sprintf("<meta name='description' content='%s'><meta name='keywords' content='%s'>",$description,$keywords);

}


// 自定义页面加载特殊css样式
function orange_customizer_custom_css() {
    wp_enqueue_style('orange_customizer_custom_css', get_template_directory_uri() . '/css/orange_customizer_custom_css.css');
}
add_action('customize_controls_print_styles', 'orange_customizer_custom_css');

// 将WordPress上传的文件名中带有中文的部分自动转化为英文以方便不同系统之间的迁移和兼容性。
add_filter('sanitize_file_name','wpceo_chinese_char');
function wpceo_chinese_char($string){
    return preg_replace_callback('/[\x{0080}-\x{ffff}]/u','wpceo_get_hex_by_callback',$string);
}
function wpceo_get_hex_by_callback($string){
    $string = (string)$string[0];
    return bin2hex($string);
}

function Bing_404_page_mail(){
    if( !is_404() ) return;//如果不是 404 页面就退出函数
    $to = get_option( 'admin_email' );//获取管理员地址
    $subject = __( '遇到 404 页面啦！', 'orange' );//邮件标题
    $message = __( '404 页面的地址：', 'orange' ) . 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '，IP:' . $_SERVER['REMOTE_ADDR'];
    wp_mail( $to, $subject, $message );//发送邮件
}

// add_action( 'wp_head', 'Bing_404_page_mail' );

// 设置保存版本修订的次数为1次
add_filter( 'wp_revisions_to_keep', 'orange_revision_times', 10, 2 );

function orange_revision_times( $num, $post ) {
    return 1;
}

/**
 * 修复WordPress找回密码提示“抱歉，该key似乎无效”问题
*/
function reset_password_message( $message, $key ) {
    if ( strpos($_POST['user_login'], '@') ) {
        $user_data = get_user_by('email', trim($_POST['user_login']));
    } else {
        $login = trim($_POST['user_login']);
        $user_data = get_user_by('login', $login);
    }
    $user_login = $user_data->user_login;
    $msg .= __( "文沥小乱提醒您：", 'orange' );
    $msg .= __( '有人要求重设如下帐号的密码：', 'orange' ). "\r\n\r\n";
    $msg .= network_site_url() . "\r\n\r\n";
    $msg .= sprintf(__( '用户名：%s', 'orange' ), $user_login) . "\r\n\r\n";
    $msg .= __( '若这不是您本人要求的，请忽略本邮件，一切如常。', 'orange' ) . "\r\n\r\n";
    $msg .= __( '要重置您的密码，请打开下面的链接：', 'orange' ). "\r\n\r\n";
    $msg .= network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') ;
    return $msg;
}
add_filter('retrieve_password_message', 'reset_password_message', 10, 2);

// Redefine user notification function
if ( !function_exists('wp_new_user_notification') ) {
    function wp_new_user_notification( $user_id, $plaintext_pass = '' ) {
        $user = new WP_User($user_id);
  
        $user_login = stripslashes($user->user_login);
        $user_email = stripslashes($user->user_email);
  
        $message  = sprintf( __( '有新用户注册，在你的网站---%s:', 'orange' ), get_option('blogname') ) . "rnrn";
        $message .= sprintf( __( '用户名: %s', 'orange' ), $user_login ) . "rnrn";
        $message .= sprintf( __( '邮件: %s', 'orange' ), $user_email ) . "rn";
  
        @wp_mail(get_option('admin_email'), sprintf( __( '[%s] 新用户注册', 'orange' ), get_option('blogname')), $message);
  
        if ( empty($plaintext_pass) )
            return;
  
        $message  = __( '你好,', 'orange') . "rnrn";
        $message .= sprintf( __( "欢迎来到 %s! 在这里登录：" , 'orange' ), get_option('blogname')) . "rnrn";
        $message .= wp_login_url() . "rn";
        $message .= sprintf( __( '用户名: %s', 'orange' ), $user_login) . "rn";
        $message .= sprintf( __( '密码: %s', 'orange' ), $plaintext_pass) . "rnrn";
        $message .= sprintf(__( '如果你遇到了什么问题, 请联系这个邮箱： %s.', 'orange' ), get_option('admin_email')) . "rnrn";
        $message .= __( 'Adios!', 'orange' );
  
        wp_mail($user_email, sprintf( __( '[%s] Your username and password', 'orange' ), get_option('blogname') ), $message);
  
    }
}

// enqueue login css
function orange_login_css(){
    wp_enqueue_style( 'orange_login_css', get_template_directory_uri() . '/css/login.css' );
}
add_action('login_head', 'orange_login_css');

// customize login footer
function orange_login_footer(){
    echo "<h3><center>" . __( '湖南文沥欢迎您！', 'orange' ) . "</center></h3>";
}
add_action( 'login_footer', 'orange_login_footer', 10, 1 );
// add_action( 'login_head', 'orange_login_footer', 10, 1 );

// customize login header url
function orange_login_headerurl($url){
    return site_url();
}
add_filter( 'login_headerurl', 'orange_login_headerurl', 10, 1 );

// customize login header title
function orange_login_headertitle(){
    return get_bloginfo('name');
}
add_filter( 'login_headertitle', 'orange_login_headertitle', 10, 1 );

/* comment_mail_notify v1.0 by willin kan. */
function comment_mail_notify($comment_id) {
    $comment = get_comment($comment_id);
    $parent_id = $comment->comment_parent ? $comment->comment_parent : '';
    $spam_confirmed = $comment->comment_approved;
    if (($parent_id != '') && ($spam_confirmed != 'spam')) {
        $wp_email = 'no-reply@welinkcredit.com'; //e-mail 发出点, no-reply 可改为可用的 e-mail.
        $to = trim(get_comment($parent_id)->comment_author_email);
        $subject = __( '您在 [', 'orange' ) . get_option("blogname") . '] 的留言有了回复';
        $message = '<p>' . trim(get_comment($parent_id)->comment_author) . ', 您好!</p>
            <p><strong>您曾在《' . get_the_title($comment->comment_post_ID) . '》的留言:</strong><br />'
            . trim(get_comment($parent_id)->comment_content) . '</p>
            <p><strong>' . trim($comment->comment_author) . ' 给您的回复:</strong><br />'
            . trim($comment->comment_content) . '<br /></p>
            <p>您可以点击 <a href="' . htmlspecialchars(get_comment_link($parent_id)) . '" target="_blank">查看回复完整內容</a></p>
            <p><a href="'. get_option( 'siteurl' ) .'" target="_blank">' . get_option('blogname') . '</a></p>
            <p>(此邮件由系统自动发送，请勿回复.)</p>';
        $from = "From: \"" . get_option('blogname') . "\" <$wp_email>";
        $headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n";
        wp_mail( $to, $subject, $message, $headers );
    }
}
add_action('comment_post', 'comment_mail_notify');

/*多站点的注册页面样式优化*/
function orange_signup_form(){
    wp_enqueue_style( 'signup-form-style', get_template_directory_uri() . '/css/signup-form.css', [], ORANGE_VERSION, 'all' );
    wp_enqueue_script( 'sign-form-script', get_template_directory_uri() . '/scripts/signup-form.js', [], ORANGE_VERSION, true );
}
add_action( 'before_signup_form', 'orange_signup_form' );

/*中英文站点banner显示*/
function _e_banner( $banner_code = 1 ){
    $banners = array(
            array( 'en_US' => '/images/img-en/dslsd-en.jpg' , 'zh_CN' => '/images/1.jpg' ),
            array( 'en_US' => '/images/img-en/dslsd-en.png', 'zh_CN' => '/images/banner.png' ),
            array( 'en_US' => '/images/img-en/gcrzd-en.jpg', 'zh_CN' => '/images/3.jpg' )
        );

    echo get_template_directory_uri() . $banners[$banner_code][get_locale()];
}

/**
 * get visitor ip
 * @return [type] [description]
 */
function get_visitor_ip(){
    if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }elseif ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return apply_filters( 'get_ip', $ip );
}

add_shortcode( 'shop_ip_address', 'get_visitor_ip' );

add_filter( 'widget_tag_cloud_args', 'filter_tag_cloud_widget' );
function filter_tag_cloud_widget() {
    $args = array(
        'echo'          => false,
        'smallest'      => 12,
        'largest'       => 12
    );
    return $args;
}
/* 初始化编辑器宽度 */
add_filter('tiny_mce_before_init', 'fb_change_mce_buttons');
function fb_change_mce_buttons( $initArray ) {
    $initArray['width'] = '750px';
    return $initArray;
}